package com.cloudcc.mobile.view.dynamic.relevant;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.util.DialogUtils.OnDoClickListener;
import com.cloudcc.mobile.util.RevlevantDialogUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.dynamic.RelevantActivtiy;
import com.cloudcc.mobile.view.login.LoginNewActivity;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase;
import com.cloudcc.mobile.weight.ui.PullToRefreshBase.OnRefreshListener;
import com.cloudcc.mobile.weight.ui.PullToRefreshWebView;

public class RelevantWebFragment extends BaseFragment {
	private PullToRefreshWebView weixinview;
	private WebView mWebView;
	private ImageView fanhui;
	private ImageView shuaxin;
	private final int PINK_RESULT=2;
	private final static String DATE_FORMAT_STR = "yyyy年MM月dd日 HH:mm";
	private ImageView menubtn;
	private RelativeLayout caozuo;
	private String urlString;
	private RelativeLayout webview;
	private LinearLayout network;
	private ValueCallback<Uri> mUploadMessage;
	private SharePreferece share;
	private CustomProgressDialog progressDialog;
	private boolean isNoShuaXin=true;
	private boolean isNoFirst=false;
	private String mUrl =StringUtils.EMPTY;

	@Override
	public void init() {
		super.init();
		mUrl =((RelevantActivtiy)getActivity()).mUrl;
		setView();
		addListener();
	}
	
	@Override
	public int getLayoutId() {
		return R.layout.relevant_web;
	}

	private void setView() {
		weixinview=(PullToRefreshWebView)convertView.findViewById(R.id.weixin);
		mWebView=weixinview.getRefreshableView();
		fanhui=(ImageView)convertView.findViewById(R.id.fanhui);
		shuaxin=(ImageView)convertView.findViewById(R.id.shuaxin);
		menubtn=(ImageView)convertView.findViewById(R.id.webview_menubtn);
		caozuo=(RelativeLayout)convertView.findViewById(R.id.caozuo);
		caozuo.setVisibility(View.GONE);
		webview=(RelativeLayout)convertView.findViewById(R.id.webview_yemian);
		network=(LinearLayout)convertView.findViewById(R.id.network_bad);
		share=new SharePreferece(mContext);
		caozuo.setVisibility(View.GONE);
		progressDialog = CustomProgressDialog.createDialog(mContext);  
		webview();
		setLastUpdateTime();
	}
	/**
	 * webview操作类
	 */
	@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
	public void webview() {
		//weixin.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//防止滑动的时候闪屏
		LogUtils.d("webview","网页路径："+mUrl);
		WebSettings webstting=mWebView.getSettings();
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj"); 
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);   
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);
		webstting.setCacheMode(WebSettings.LOAD_DEFAULT);//是否缓存
		webstting.setBlockNetworkImage(false);//后来加的
		mWebView.setWebViewClient(new MyWebClient());
		mWebView.setWebChromeClient(new MyWebChromeClient());
		mWebView.loadUrl(mUrl);
	}

	final class InJavaScriptLocalObj {  
		public void showSource(String html) {
			int a=html.indexOf(":");
			html=html.substring(a+1, html.length());
			AppContext.relevantName=html;
		}  
	}  
	protected void setLastUpdateTime() {
		weixinview.setLastUpdatedLabel(new SimpleDateFormat(DATE_FORMAT_STR, Locale.CHINA).format(new Date()));
	}

	Handler handler=new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				startProgressDialog();
				break;
			case 2:
				stopProgressDialog();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	private SharedPreferences preferences;

	@SuppressLint("SdCardPath")
	@Override
	public void onActivityResult(int requestCode, int resultCode,Intent intent) {  
		if(requestCode==PINK_RESULT)  {  
			if (null == mUploadMessage) return;  
			Uri result = intent == null || resultCode != getActivity().RESULT_OK ? null  
					: intent.getData();  
			mUploadMessage.onReceiveValue(result);  
			mUploadMessage = null;  
		}
	}  

	/**
	 * dialog开始显示
	 */
	private void startProgressDialog(){  
		if (progressDialog == null){  
			progressDialog = CustomProgressDialog.createDialog(mContext);  
			progressDialog.setCancelable(true);
			progressDialog.setCanceledOnTouchOutside(false);
			//			progressDialog.setMessage("正在加载中...");  
		}  
		progressDialog.show();  
	}  
	/**
	 * 停止dialog
	 */
	private void stopProgressDialog(){  
		if (progressDialog != null){  
			progressDialog.dismiss();  
			progressDialog = null;  
		}  
	} 

	/**
	 * 监听   mWebView.goBack();   //后退  
           mWebView.goForward();//前进
           mWebView.reload();  //刷新
	 */
	private void addListener() {
		weixinview.setOnRefreshListener(new OnRefreshListener<WebView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<WebView> refreshView) {
				mWebView.reload(); 
				isNoShuaXin=false;
				weixinview.onPullDownRefreshComplete();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<WebView> refreshView) {
			}
		});
		network.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mWebView.reload();    //刷新
				AppContext.isFirst=true;
				AppContext.isError=false;
			}
		});
		menubtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				EventEngine.post(new MenuToggleEvent(false, false));
			}
		});
		fanhui.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {
			if(urlString.equals(UrlTools.weixinUrl+UrlTools.menuurl)){
				mWebView.reload();    //刷新
			}else{
				mWebView.goBack();   //后退  
			}
		}});
		shuaxin.setOnClickListener(new OnClickListener() {@Override public void onClick(View v) {
			mWebView.reload();    //刷新
		}});

	}

	private void isFirst() {
		preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
		boolean firstTime = preferences.getBoolean("firs_time", true);
		if (firstTime){
			Editor pEdit = preferences.edit();
			pEdit.putBoolean("firs_time", false);
			pEdit.commit();
			RevlevantDialogUtils.isFirstDialog(mContext);
		}
	}
	
	private class MyWebClient extends WebViewClient{

		@Override
		public void onPageStarted(WebView view, String url,
				Bitmap favicon) {
			LogUtils.d("webview","start:"+url);
			super.onPageStarted(view, url, favicon);
			if(url.equals(AppContext.indexUrl)){
				EventEngine.post(new MenuToggleEvent(false, false));
				mWebView.stopLoading();
				return;
			}
			handler.sendEmptyMessage(1);
			if(url.equals(UrlTools.loginurl)){
				Intent intent=new Intent(UrlTools.loginurl);
				mContext.sendBroadcast(intent);
			}
			urlString=url;
			
		}
		@Override
		public void onPageFinished(WebView view, String url) {
			LogUtils.d("webview","finished:"+url);
			super.onPageFinished(view, url);
			try {
				if(url.contains("/weiquery.action?id=")){
					if(url.indexOf("#")!=-1){//包含# 号
						String type=url.substring(Tools.getCharacterPosition(url,"=",4)+1, url.length());
						if(type.equals("query")){
							String id=url.substring(Tools.getCharacterPosition(url,"=",3)+1, url.length()-8);
							AppContext.record_id=id;
							Intent intent=new Intent(AppContext.RECORD_ID_CHANGED_SHUAXIN);
							mContext.sendBroadcast(intent);
						}
					}else{//不包含# 号
						String type=url.substring(Tools.getCharacterPosition(url,"=",2)+1, url.length());
						if(type.equals("query")){
							String id=url.substring(Tools.getCharacterPosition(url,"=",1)+1, url.length()-8);
							AppContext.record_id=id;
							Intent intent=new Intent(AppContext.RECORD_ID_CHANGED_SHUAXIN);
							mContext.sendBroadcast(intent);
						}
					}
				}else if(url.contains("wx_taskquery.action?id=")){
					String type=url.substring(Tools.getCharacterPosition(url,"=",2)+1, url.length());
					if(type.equals("query")){
						String id=url.substring(Tools.getCharacterPosition(url,"=",1)+1, url.length()-8);
						AppContext.record_id=id;
						Intent intent=new Intent(AppContext.RECORD_ID_CHANGED_SHUAXIN);
						mContext.sendBroadcast(intent);
					}

				}
			} catch (Exception e) {
				Tools.handle(e);
			}
			// 加载完了再调用js登录代码
			handler.sendEmptyMessage(2);
			setLastUpdateTime();//刷新时间
			if(AppContext.isError){
				mWebView.setVisibility(View.GONE);
				caozuo.setVisibility(View.GONE);
				network.setVisibility(View.VISIBLE);
				if(!AppContext.isFirst){
					AppContext.isError=false;
				}
				AppContext.isFirst=false;
			}else{
				AppContext.isFirst=true;
				mWebView.setVisibility(View.VISIBLE);
				caozuo.setVisibility(View.GONE);
				network.setVisibility(View.GONE);
			}
			view.loadUrl("javascript:window.local_obj.showSource( document.getElementsByTagName('title')[0].innerHTML);");  
			//view.loadUrl("javascript:window.local_obj.showSource( document.getElementsByTagName('title')[0].innerHTML);");aa  
			isNoFirst=true;
			isFirst();
			RelevantActivtiy.relevant_bottom.setVisibility(View.VISIBLE);
			RelevantActivtiy.group.setVisibility(View.VISIBLE);
		}
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			LogUtils.d("webview","跳转："+url);
			if (UrlManager.isWapLogin(url)) {// 跳转去登录
				EventEngine.register(RelevantWebFragment.this);
				Intent intent = new Intent(getActivity(), BindActivity.class);
				getActivity().startActivity(intent);
				return true;
			}
			if(isNoFirst&&isNoShuaXin){
				if(url.equals(mUrl)){
					getActivity().finish();
					mWebView.stopLoading();
					return true;
				}
			}
			//解决从协作页面加载的问题
			if (StringUtils.contains(url, "wx_lookAtRecent.action")) {
				getActivity().finish();
				return true;
			}
			if(UrlManager.isHome(url)){
				getActivity().finish();
				mWebView.stopLoading();
				return true;
			}else if(url.equals(UrlTools.weixinUrl+"/weiLogout.action")){//退出
				Intent intent=new Intent(mContext,LoginNewActivity.class);
				mContext.startActivity(intent);
				getActivity().finish();
				return true;
			}else{
				//自身加载新链接,不做外部跳转
				view.loadUrl(url);
				return true;
			}
			
		}
		public void onReceivedSslError(WebView view, android.webkit.SslErrorHandler handler, android.net.http.SslError error) {
			LogUtils.d("webview","出现错误了1");
			handler.proceed();  
		};
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			AppContext.isError=true;
			LogUtils.d("webview","出现错误了2");
			return;
		}
	
	}
	
	private class MyWebChromeClient extends WebChromeClient{

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			super.onProgressChanged(view, newProgress);
		}
		@Override
		public boolean onJsAlert(WebView view, String url,
				String message, final JsResult result) {
			return true;
		}
		@Override
		public boolean onJsConfirm(WebView view, String url,
				String message, final JsResult result) {
			DialogUtils dialogutils=new DialogUtils(mContext);
			dialogutils.showUpdateDialog(mContext, "网页提示", message);
			dialogutils.setOnDoClicktListener(new OnDoClickListener() {
				@Override
				public void confirm() {
					result.confirm(); 
				}
				@Override
				public void cancel() {
					result.cancel();
				}
			});
			return true;
		}
		public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {  
			if (mUploadMessage != null) return;
			mUploadMessage = uploadMsg;   
			Intent i = new Intent(Intent.ACTION_GET_CONTENT);
			i.addCategory(Intent.CATEGORY_OPENABLE);
			i.setType("*/*");
			startActivityForResult( Intent.createChooser( i, "选择文件" ), PINK_RESULT);
		}

		// For Android  > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
			openFileChooser(uploadMsg, acceptType);
		}
		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			openFileChooser( uploadMsg, "" );
		}
	
		@Override
		public void onReceivedTitle(WebView view, String title) {
			super.onReceivedTitle(view, title);
			new InJavaScriptLocalObj().showSource(title);
		}
	}
	
	public void onEventMainThread(StartWebEvent event) {
		if (event.isError()) {
			getActivity().finish();
			return;
		}
		mWebView.loadUrl(mUrl);
		EventEngine.uregister(this);
	}
}
